package com.gmq.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class Upload {
    @Autowired
    private AilOss ailOss;
    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        //读取值
        String endpoint = ailOss.getEndpoint();
        String accessKeyId = ailOss.getAccessKeyId();
        String accessKeySecret = ailOss.getAccessKeySecret();
        String bucketName = ailOss.getBucketName();
        String url = ailOss.getUrl();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件的后缀的下标
        int index = file.getOriginalFilename().indexOf('.');
        //获取文件后缀
        String last = file.getOriginalFilename().substring(index);
        //避免重复使用uuid作为文件名
        String uuid = UUID.randomUUID() + last;
        try {
            //上传文件
            //获取字节输入流
            InputStream inputStream = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uuid, inputStream);
            ossClient.putObject(putObjectRequest);
            //拼接返回的文件名
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(url).append("/").append(uuid);
            return stringBuilder.toString();
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }
}
